package lq.common.handler;

import lombok.extern.slf4j.Slf4j;
import lq.common.entity.StudyResponse;
import lq.common.exception.StudyAuthException;
import lq.common.exception.StudyException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Set;

/**
 * @program: cloud-study
 * @description: 全局异常处理器, 进行通用捕获, 每个服务都一样的
 * 主要处理的是controller层抛出的异常
 * 因为controller层抛出的异常在各个服务都需要用到,所以放在公共module里面
 * @author: LQ
 * @create: 2020-10-12 15:42
 */
@Slf4j
public class BaseExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public StudyResponse handleException(Exception e) {
        log.error("系统内部异常，异常信息", e);
        return new StudyResponse().message("系统内部异常");
    }

    @ExceptionHandler(value = StudyAuthException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public StudyResponse handleFebsAuthException(StudyAuthException e) {
        log.error("系统错误", e);
        return new StudyResponse().message(e.getMessage());
    }

    @ExceptionHandler(value = AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public StudyResponse handleAccessDeniedException() {
        return new StudyResponse().message("没有权限访问该资源");
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = StudyException.class)
    public StudyResponse handleStudyException(StudyException e) {
        log.error("系统错误", e);
        return new StudyResponse().message(e.getMessage());
    }

    /**
     * 统一处理请求参数校验(普通传参)
     * <p>
     * controller上使用@NotBlank等注解验证参数的时候,
     * 如果参数不正确,会抛出ConstraintViolationException异常
     *
     * @param e ConstraintViolationException异常信息
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public StudyResponse handleConstraintViolationException(ConstraintViolationException e) {
        StringBuilder message = new StringBuilder();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            Path path = violation.getPropertyPath();
            String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), ".");
            message.append(pathArr[1]).append(violation.getMessage()).append(",");
        }
        String messageStr = message.substring(0, message.length() - 1);
        return new StudyResponse().message(messageStr);
    }

    /**
     * 统一处理请求参数校验(实体对象传参)
     * 在使用@Valid注解验证的实体对象的时候,如果验证不通过,会抛出BindException异常
     *
     * @param e BindException
     * @return FebsResponse
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public StudyResponse handleBindException(BindException e) {
        StringBuilder message = new StringBuilder();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(",");
        }
        String messageString = message.substring(0, message.length() - 1);
        return new StudyResponse().message(messageString);
    }


}
